﻿using LPBToolsLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AUSer_V1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public Dictionary<string, object> tRecReqDatas { get; private set; }
        public Dictionary<string, object> ResponseValues { get; private set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            string sMD5Test = "this is login password";
            MD5 md5 = MD5.Create();//实例化
            byte[] buffer = Encoding.UTF8.GetBytes(sMD5Test);
            byte[] bufferMd5 = md5.ComputeHash(buffer);
            sMD5Test = BaseTools.BytesToStrHex(bufferMd5).Replace(" ", string.Empty).ToLower();
            string DBType = WebConfigurationManager.AppSettings["DBType"];

            string SysToken = WebConfigurationManager.AppSettings["SysToken"]; ;
            bool isDebug = false;

            if (string.IsNullOrEmpty(SysToken))
                SysToken = Guid.NewGuid().ToString().Replace("-", string.Empty).ToUpper();

            string sRespon = "";
            tRecReqDatas = null;
            JavaScriptSerializer tSerializer = new JavaScriptSerializer();
            // 初始化用请求应答
            ResponseValues = new Dictionary<string, object>();
            ResponseValues.Add("err", 0);
            ResponseValues.Add("msg", "ready");
            ResponseValues.Add("reqtype", "get");
            if (isDebug)
            {
                ResponseValues.Add("SysToken", SysToken);
                ResponseValues.Add("DBType", DBType);
                if (AUSLogin.tDBConfig != null)
                {
                    ResponseValues.Add("DBAddress", AUSLogin.tDBConfig.Address);
                    ResponseValues.Add("DBPort", AUSLogin.tDBConfig.DBPort);
                    ResponseValues.Add("DBUser", AUSLogin.tDBConfig.DBUser);
                    ResponseValues.Add("DBPass", AUSLogin.tDBConfig.DBPass);
                }
            }

            Response.Clear();
            Response.ContentType = "application/json";
            Response.Charset = "utf-8";
            try
            {
                // POST类型请求，提取Post数据
                Stream sRecDataStream = Request.InputStream;
                if (sRecDataStream.Length > 0)
                {
                    ResponseValues["type"] = "post";
                    byte[] tRecBuf = new byte[sRecDataStream.Length];
                    sRecDataStream.Read(tRecBuf, 0, (int)sRecDataStream.Length);
                    try
                    {
                        string sTmp = Encoding.UTF8.GetString(tRecBuf);
                        tRecReqDatas = (Dictionary<string, object>)tSerializer.DeserializeObject(sTmp);
                        ResponseValues.Add("pdata", tRecReqDatas);
                    }
                    catch (Exception ex)
                    {
                    }
                }
                ResponseValues.Add("url", Request.Url.ToString());
                string sAPIName = Request.QueryString["api"];
                if (!string.IsNullOrEmpty(sAPIName))
                {
                    ResponseValues.Add("api", sAPIName);

                    if (tRecReqDatas == null)
                        tRecReqDatas = new Dictionary<string, object>();

                    // 将Query参数也放入tRecPostDatas中
                    string[] tQKeys = Request.QueryString.AllKeys;
                    foreach (string key in tQKeys)
                        if (!tRecReqDatas.ContainsKey(key))
                            tRecReqDatas.Add(key, Request.QueryString[key]);
                    //ResponseValues.Add("gdata", tRecReqDatas);

                    string sErrMsg = "";
                    int iErrCode = 0;
                    // 所有参数全部放入tRecPostDatas
                    switch (sAPIName.ToLower())
                    {
                        case "login":
                            //AUSLogin.StationLogin()
                            Dictionary<string, object> tResult = AUSLogin.StationLogin(tRecReqDatas, out iErrCode, out sErrMsg);
                            if ((iErrCode >= 0) && (tResult != null) && (tResult.Count > 0))
                            {
                                ResponseValues.Add("loginresult", tResult);
                            }
                            break;
                        default:
                            iErrCode = -1;
                            ResponseValues["err"] = -1;
                            ResponseValues["msg"] = "unknow";
                            break;
                    }
                    ResponseValues["err"] = iErrCode;
                    ResponseValues["msg"] = sErrMsg;
                }
                // 应答
                sRespon = tSerializer.Serialize(ResponseValues);
            }
            catch
            {
                sRespon = "";
            }
            finally
            {
                if (!string.IsNullOrEmpty(sRespon))
                {
                    Response.Write(sRespon);
                    Response.Flush();
                }
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }

        void doWithAppQuery(Dictionary<string, object> sQueryResult, string sErrMsg)
        {
            if (sQueryResult != null)
            {
                ResponseValues["err"] = 0;
                ResponseValues["msg"] = sErrMsg;
                if (ResponseValues.ContainsKey("result"))
                    ResponseValues["result"] = sQueryResult;
                else
                    ResponseValues.Add("result", sQueryResult);
            }
            else
            {
                ResponseValues["err"] = -3;
                ResponseValues["msg"] = sErrMsg;
            }
        }
    }
}